﻿// Write a program that fills and prints a matrix of size (n, n) / Point D (Numbers in spiral)

using System;

class PrintMatrixPointD
{
    static void Main()
    {
        // read from console
        Console.Write("Enter Matrix size (n): ");
        int size = int.Parse(Console.ReadLine());

        int row = 0;
        int col = 0;
        string direction = "down";
        int[,] matrix = new int[size, size];
        for (int i = 1; i <= size * size; i++)
        {
            matrix[row, col] = i;
            if (direction == "down")
            {
                row++;
                if (row == size - 1 || matrix[row + 1, col] != 0)
                {
                    direction = "right";
                }
            }
            else if (direction == "right")
            {
                col++;
                if (col == size - 1 || matrix[row, col + 1] != 0)
                {
                    direction = "up";
                }
            }
            else if (direction == "up")
            {
                row--;
                if (row == 0 || matrix[row - 1, col] != 0)
                {
                    direction = "left";
                }
            }
            else if (direction == "left")
            {
                col--;
                if (col == 0 || matrix[row, col - 1] != 0)
                {
                    direction = "down";
                }
            }
        }

        // print matrix
        for (row = 0; row < matrix.GetLength(0); row++)
        {
            for (col = 0; col < matrix.GetLength(1); col++)
            {
                Console.Write("{0, 4}", matrix[row, col]);
                if (row != matrix.GetLength(0) - 1 || col != matrix.GetLength(1) - 1)
                {
                    Console.Write(", ");
                }
            }
            Console.WriteLine();
        }
    }
}